using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

namespace Voodoo.Sauce.Internal.CrossPromo.Canvas
{
	internal class SquareFormat : AFormatManager
	{
		private VideoManager _videoManager;

		private int _retries;

		private void Awake()
		{
			AFormatManager.Instance = this;
			_retries = 1;
			base.gameObject.name = "CrossPromoGameObject";
			CrossPromoDisplayEvents.ShowEvent += Display;
			CrossPromoDisplayEvents.HideEvent += Hide;
		}

		private void OnDestroy()
		{
			CrossPromoDisplayEvents.ShowEvent -= Display;
			CrossPromoDisplayEvents.HideEvent -= Hide;
		}

		private void Start()
		{
			try
			{
				_videoManager = new VideoManager(GetComponentInChildren<VideoPlayer>(), GetComponentInChildren<RawImage>());
				_videoManager.VideoPlayer.loopPointReached += delegate
				{
					_videoManager.Content.enabled = false;
					Display();
				};
				_videoManager.VideoPlayer.prepareCompleted += delegate
				{
					_videoManager.Content.enabled = true;
					CrossPromoEvents.TriggerShownEvent(Asset);
				};
			}
			catch (Exception)
			{
			}
		}

		public override void Display()
		{
			Asset = null;
			IsActive = true;
			if (!IsWaiting)
			{
				StartCoroutine(StartDisplay());
			}
		}

		private IEnumerator StartDisplay()
		{
			IsWaiting = true;
			yield return new WaitForEndOfFrame();
			yield return WaitCrossPromoReady();
			IsWaiting = false;
			if (!IsActive || Asset == null)
			{
				if (!IsActive)
				{
					Hide();
				}
				else
				{
					_videoManager.StopVideo();
				}
				StartCoroutine(Retry());
				yield break;
			}
			_retries = 1;
			try
			{
				_videoManager.PrepareVideo(Asset);
			}
			catch (Exception message)
			{
				CrossPromoEvents.TriggerErrorEvent(message);
			}
		}

		private void OnDisable()
		{
			IsWaiting = false;
			Hide();
		}

		private void OnEnable()
		{
			IsWaiting = false;
		}

		public override void Hide()
		{
			IsActive = false;
			IsWaiting = false;
			_retries = 1;
			_videoManager?.StopVideo();
		}

		private IEnumerator Retry()
		{
			if (_retries <= 10)
			{
				int num = (int)Math.Pow(2.0, _retries);
				_retries++;
				yield return new WaitForSeconds(num);
				while (!IsActive)
				{
					yield return null;
				}
				Display();
			}
		}
	}
}
